/*
   Copyright 2009-2010 the original author or authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package com.googlecode.kohmori.reportgen;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.sql.Connection;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.util.JAXBSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import com.googlecode.kohmori.springmvc.LoginReportParams;
import com.googlecode.kohmori.springmvc.DefaultReportParams;

import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.Fop;

public abstract class AbstractReportGenerator {
   protected AbstractSQLSource sqlSource = null;
   protected String xslFilePath;
   protected String testXMLFilePath;
   private static URL dbFileURL = null;
   protected String reportType = null; // set to PDF, RTF, etc. in subclasses

   protected void addTransformerParameters(Transformer transformer,
         DefaultReportParams rP) {
   }

   public String getTestXMLFilePath() {
      return testXMLFilePath;
   }

   public void setTestXMLFilePath(String testXMLFilePath) {
      this.testXMLFilePath = testXMLFilePath;
   }

   public String getXslFilePath() {
      return xslFilePath;
   }

   public void setXslFilePath(String xslFilePath) {
      this.xslFilePath = xslFilePath;
   }

   public AbstractSQLSource getSqlSource() {
      return sqlSource;
   }

   public void setSqlSource(AbstractSQLSource sqlSource) {
      this.sqlSource = sqlSource;
   }

   protected JDBCConnObj getJDBCConnObj() throws Exception {
      if (dbFileURL == null) {
         dbFileURL = getClass().getClassLoader().getResource("databases.xml");

         if (dbFileURL == null) {
            throw new IllegalStateException(
                  "Cannot find database listing file.");
         }
      }
      return new JDBCConnObj(dbFileURL);
   }

   public ByteArrayOutputStream createReportBAOS(Connection conn,
         DefaultReportParams rP) throws Exception {
      ByteArrayOutputStream reportBaos = new ByteArrayOutputStream();
      OutputStream out = new java.io.BufferedOutputStream(reportBaos);
      createReport(conn, rP, out, null);
      return reportBaos;
   }

   public void createReportFile(Connection conn, DefaultReportParams rP,
         String reportFileName) throws Exception {
      createReport(conn, rP, null, reportFileName);
   }

   private void createReport(Connection inConn, DefaultReportParams rP,
         OutputStream outStream, String reportFileName) throws Exception {
      Connection conn;
      TransformerFactory factory = TransformerFactory.newInstance();
      boolean providedConn = false;

      if (inConn == null) { // using login parameters
         JDBCConnObj jco = getJDBCConnObj();
         if (rP instanceof LoginReportParams) {
            LoginReportParams lRP = (LoginReportParams) rP;
            jco.connectToDatabase(lRP.getUsername(), lRP.getPassword(), lRP
                  .getDatabaseName());
         } else {
            throw new IllegalArgumentException(
                  "(internal error) No database "
                        + "connection provided; report params must extend LoginReportParams");
         }
         conn = jco.getDBConn();
      } else {
         providedConn = true;
         conn = inConn;
      }

      JAXBElement<?> jaxbElement = sqlSource.createReportObject(conn, rP);
      String jaxbPackageList = sqlSource.getJAXBPackageList();
      JAXBContext jc = JAXBContext.newInstance(jaxbPackageList);      
      Marshaller m = jc.createMarshaller();
      
/*    // Debug #1: See the XML generated
      System.out.println("Marshalling via JAXB");
      m.marshal(jaxbElement, new FileOutputStream("SourceXML.xml"));
*/      
      
      Source rptSource = new JAXBSource(m, jaxbElement);
      URL stylesheetURL;
      if (xslFilePath != null) {
         stylesheetURL = getClass().getClassLoader().getResource(xslFilePath);
         if (stylesheetURL == null) {
            throw new IllegalArgumentException(
                  "Error:  Cannot find resource for xslFilePath = "
                        + xslFilePath);
         }
      } else {
         throw new IllegalArgumentException(
               "Error:  xslFilePath not configured.");
      }
      Transformer transformer = factory.newTransformer(new StreamSource(
            stylesheetURL.toString()));
      addTransformerParameters(transformer, rP);

/*    // Debug option #2: Use a hardcoded XML to test stylesheet
      if (rP.getUseTestFile()) {
         if (testXMLFilePath == null || testXMLFilePath.length() == 0) {
            throw new IllegalStateException("No test XML data provided.");
         }
         rptSource = new StreamSource(testXMLFilePath);
         System.out.println("Using test file " + testXMLFilePath
               + " to generate output report.");
      }
*/
      if (reportFileName != null) {
         outStream = new java.io.FileOutputStream(reportFileName);
      }

/*    // Debug Option #3: see XSL-FO document (XSLT transform only)
      transformer.transform(rptSource, new javax.xml.transform.stream.StreamResult
            (new FileOutputStream("XSLFODoc.xml")));
*/
      
      FopFactory fopFactory = FopFactory.newInstance();
      Fop fop = fopFactory.newFop(reportType, outStream);
      Result res = new SAXResult(fop.getDefaultHandler());

      transformer.transform(rptSource, res);
      outStream.close();
      if (!providedConn) {
         conn.close();
      }
   }

}
